package com.karry.yl.web.food;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.karry.commons.base.SuperController;
import com.karry.commons.util.TimeUtil;
import com.karry.commons.vo.LayTableResponse;
import com.karry.yl.domain.food.FoodSampleModel;
import com.karry.yl.service.food.FoodSampleService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * 菜谱管理Controller
 *
 * @author Administrator
 */
@Controller
@RequestMapping("/foodSample")
public class FoodSampleController extends SuperController {

    @Autowired
    private FoodSampleService foodSampleService;

    /**
     * 到报修列表页
     *
     * @return
     */
    @RequestMapping
    public String listUI() {
        return "food/menu/sample/list";
    }

    @RequestMapping("/add")
    public String addUI(ModelMap map) {
        return "food/menu/sample/add";
    }

    @RequestMapping("edit")
    public String editUI(Long id, ModelMap map) {
        FoodSampleModel foodSampleModel = foodSampleService.selectById(id);
        map.put("foodSampleModel", foodSampleModel);
        return "food/menu/sample/edit";
    }


    @RequestMapping("/list")
    @ResponseBody
    public LayTableResponse listUI(int page, int limit) {
        Page<FoodSampleModel> foodSamplePage = foodSampleService.selectPage(new Page<FoodSampleModel>(page, limit), new EntityWrapper<FoodSampleModel>().eq("orgId", currentUser.getOrgId()).orderBy("createdTime",false));
        return new LayTableResponse(foodSamplePage.getRecords(), foodSamplePage.getTotal());
    }

    @RequestMapping("/save")
    public String save(FoodSampleModel foodSampleModel) {
        foodSampleModel.setOrgId(currentUser.getOrgId());
        foodSampleModel.setSampleUser(currentUser.getUserName());
        foodSampleService.insert(foodSampleModel);
        return "redirect:/foodSample";
    }

    @RequestMapping("/update")
    public String update(FoodSampleModel foodSampleModel) {
        foodSampleModel.setOrgId(currentUser.getOrgId());
        foodSampleService.updateById(foodSampleModel);
        return "redirect:/foodSample";
    }

    /**
     * 删除
     *
     * @param
     * @return
     */
    @RequestMapping(path = "/delete")
    public String delete(@RequestParam("id") List<Long> ids) {
        foodSampleService.deleteBatchIds(ids);
        return "redirect:/foodSample";
    }

    /**
     * 报修记录导出为excel
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping("/export/excel")
    public void exportExcel(HttpServletResponse response) {
        //查询时间段菜谱
        List<FoodSampleModel> foods = foodSampleService.selectList(new EntityWrapper<FoodSampleModel>().eq("orgId", currentUser.getOrgId()));
        //生成Excel,并存储临时文件
        // 创建一个HSSFWorkbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("留样记录");
        // 表头
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
        //声明列对象
        HSSFCell cell = null;
        //创建标题
        String[] title = {"菜名",  "留样人", "留样时间"};
        for (int i = 0; i < title.length; i++) {
            row.setHeightInPoints(20);
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
            sheet.setColumnWidth(i, 21 * 256);
        }
        //创建内容
        for (int i = 0; i < foods.size(); i++) {
            row = sheet.createRow(i + 1);
            row.setHeightInPoints(20);
            sheet.setColumnWidth(i + 1, 21 * 256);
            FoodSampleModel foodSampleModel = foods.get(i);
            row.createCell(0).setCellValue(foodSampleModel.getFoodName());
            row.createCell(1).setCellValue(foodSampleModel.getSampleUser());
            row.createCell(2).setCellValue(TimeUtil.format(foodSampleModel.getCreatedTime(), "yyyy-MM-dd HH:mm:ss") );
        }
        //下载
        response.setCharacterEncoding("UTF-8");
        try (ServletOutputStream out = response.getOutputStream();) {
            response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode("留样记录-" + TimeUtil.format(new Date(), "yyyyMMddHHmmss") + ".xls", "UTF-8"));
            wb.write(out);
        } catch (IOException e) {
            //TODO 下载失败日志记录
        } finally {
            try {
                wb.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
